package service.forkinjoin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveAction;

import javax.mail.Message;
import javax.mail.MessagingException;

import service.EmailUtil;

public class ForkSortMessagesBySender extends RecursiveAction {

	private static final long serialVersionUID = -1092415796824205832L;
	private List<Message> listMessagesWithAttachment;
	private List<Message> listMessages;
	private String sender;

	public ForkSortMessagesBySender(List<Message> listMessagesWithAttachment, List<Message> listMessages, String sender) {
		this.listMessagesWithAttachment = listMessagesWithAttachment;
		this.listMessages = listMessages;
		this.sender = sender;
	}

	@Override
	protected void compute() {

		List<RecursiveAction> actions = new ArrayList<>();

		if (this.listMessagesWithAttachment.size() <= Runtime.getRuntime().availableProcessors()) {
			try {
				this.separateMessages();
			} catch (MessagingException | IOException e) {
				e.printStackTrace();
			}
		} else {

			int end = this.listMessagesWithAttachment.size() / 2;
			actions.add(new ForkSortMessagesBySender(this.listMessagesWithAttachment.subList(0, end), this.listMessages, this.sender));
			end += this.listMessages.size() % 2 == 0 ? 0 : 1;
			actions.add(new ForkSortMessagesBySender(this.listMessagesWithAttachment.subList(end, this.listMessagesWithAttachment.size()), this.listMessages, this.sender));
			invokeAll(actions);
		}
	}

	private void separateMessages() throws MessagingException, IOException {

		for (Message message : this.listMessagesWithAttachment) {
			if (EmailUtil.getSender(message).equals(this.sender)) {
				this.listMessages.add(message);
			}
		}
	}
}
